<script setup lang="ts">
import {computed, defineExpose, onMounted, reactive, ref} from "vue";
import {exportExcelFront} from "./export";
import {useMessage} from 'naive-ui';

const message = useMessage();
const showRangePasswordModal = ref(false);
const password = ref("");
let ls: any = null;
let rangeAut: any = null;
let inputRangeProtectionPassword: any = null;
let unableEditCellList = [];
let clickInterval = [];
defineOptions({
  name: "Excel"
})
const emit = defineEmits<{
  (e: "cellDoubleClick", cell: any, position: any, sheet: any, ctx: any): void,
  (e: "cellClick", cell: any, position: any, sheet: any, ctx: any): void
}>();
const props = defineProps<{
  config: Excel.Config
}>()
const data = reactive({
  sheetData: [],
});

const hook = {
  openRangePassword: function (aut: any, irpp: any) {
    showRangePasswordModal.value = true;
    rangeAut = aut;
    inputRangeProtectionPassword = irpp
  },
  cellMousedown: function (cell: any, position: any, sheet: any, ctx: any) {
    //实现双击效果
    if (clickInterval.length == 0) {
      clickInterval.push({
        time: new Date().getTime(),
        position: `${position.r}_${position.c}`
      });
      setTimeout(() => {
        clickInterval = [];
      }, 500)
    } else if (clickInterval.length == 1) {
      let t = clickInterval[0].time;
      let c = clickInterval[0].position;
      let n = new Date().getTime()
      if (c == `${position.r}_${position.c}` && n - t < 500) {
        emit("cellDoubleClick", cell, position, sheet, ctx);
        clickInterval = [];
      }
    }
    emit("cellClick", cell, position, sheet, ctx);
    return true;
  },
  cellEditBefore: function (range: any) {
    let column = range[0].column[0];
    let row = range[0].row[0];
    let flag = true;
    if (unableEditCellList.length > 0) {
      for (let i = 0; i < unableEditCellList.length; i++) {
        let cell = unableEditCellList[i];
        if ((cell.c == column && cell.r == row) || (cell.r == row && cell.c == -1) || (cell.r == -1 && cell.c == column)) {
          flag = false;
          break
        }
      }
    }
    // console.log("cellEditBefore:", unableEditCellList, range);
    return flag;
  },
  cellUpdateBefore: function (r: number, c: number, value: any, isRefresh: boolean) {
    // console.log("cellUpdateBefore:", r, c, value, isRefresh);
    return true
  },
  cellCleanBefore: function (store: any) {
    console.log("cellCleanBefore:", store);
    let r1 = store[0].row[0];
    let r2 = store[0].row[1];
    let c1 = store[0].column[0];
    let c2 = store[0].column[1];
    console.log("cellCleanBefore:", r1, r2, c1, c2);
    return false;
  },
  cellUpdated: function (r: number, c: number, old: any, newVal: any, isRefresh: boolean) {
    // console.log("cellUpdated:");
  }
}
const options = {
  container: 'luckysheet',
  autoload: true,
  cellRightClickConfig: {
    chart: false,
    data: false,
    cellFormat: false,
    customs: [{
      title: 'test',
      onClick: function (clickEvent, event, params) {
        let cellVal = window.luckysheet.getcellvalue(params.rowIndex, params.columnIndex);
        // console.log(cellVal)
      }
    }]
  },

}
const style = computed(() => createCss());

function confirmRangePassword() {
  if (password.value == null || password.value.length == 0) {
    message.error("请输入密码");
    return;
  }

  if (rangeAut.algorithmName != null && rangeAut.algorithmName != "None") {
    if (rangeAut.saltValue != null && rangeAut.saltValue.length > 0) {
      let hasher = CryptoApi.getHasher(rangeAut.algorithmName);
      password.value = CryptoApi.hmac(rangeAut.saltValue, password, hasher);
    } else {
      password.value = CryptoApi.hash(rangeAut.algorithmName, password);
    }
  }
  if (password.value == rangeAut.password) {

    inputRangeProtectionPassword[rangeAut.sqref] = 1;
    showRangePasswordModal.value = false;
    password.value = "";
    message.success("解锁成功");
  }
}


function setHideColumn(columnStart: number, columnEnd: number) {
  window.luckysheet.hideColumn(columnStart, columnEnd)
}

function exportExcel(name: string, excelType: string, ignorecolumns: number[]) {
  exportExcelFront(luckysheet.getAllSheets(), name, excelType, ignorecolumns)
}

function getCellData(row: number, column: number) {
  return window.luckysheet.getcellvalue(row, column)
}

function addRow(start: number, row: number) {
  window.luckysheet.insertRow(start, row)
}

function setBgColor(sheet: number, row: number, column: number, color: string) {
  window.luckysheet.setCellFormat(row, column, "bg", color, {order: sheet})
}

function setRangeMerge(sheet: number, type: string, range: string) {
  window.luckysheet.setRangeMerge(type, {range: range, order: sheet})
}

function setRangeBgColor(sheet: number, range: string, color: string) {
  window.luckysheet.setRangeFormat("bg", color, {range: [range], order: sheet})
}

function setRangeBorder(sheet: number, range: string) {
  window.luckysheet.setCellFormat("bd", {
    borderType: "border-all",
    style: "1",
    color: "#000000",
    order: sheet,
    range: range
  })
}

function getRange() {
  return window.luckysheet.getRange()
}

function setRangeShow(range: any, setting: any) {
  window.luckysheet.setRangeShow(range, setting)
}

function setCellValue(row: number, column: number, value: any, setting: any) {
  window.luckysheet.setCellValue(row, column, value, setting)
}

function reloadConfig() {
  $("#luckysheet").html('');
  Object.assign(props.config.hook, hook);
  Object.assign(options, props.config);
  ls = luckysheet.create(options);
  resize();
}

function setUnableEdit(d: any[]) {
  unableEditCellList = d;
}

function getUnableEdit() {
  return unableEditCellList;
}

function destroy() {
  window.luckysheet.destroy()
}

function resize() {

  window.luckysheet.resize()
}

function updataSheet(config: any) {
  window.luckysheet.updataSheet(config);
}

function createCss() {
  let width = props.config.width
  let height = props.config.height;
  return {
    width: width + 'px',
    height: height + 'px',
    margin: 0,
    padding: '0px',
    left: 0,
    top: '50px'
  }
}

function getSheetData() {
  data.sheetData = luckysheet.getAllSheets()
  return data.sheetData;
}

function create() {
}

defineExpose({
  getSheetData,
  reloadConfig,
  exportExcel,
  getCellData,
  addRow,
  setBgColor,
  setRangeBorder,
  setRangeBgColor,
  setRangeMerge,
  getRange,
  setHideColumn,
  setRangeShow,
  setCellValue,
  updataSheet,
  setUnableEdit,
  getUnableEdit,
  resize,
  destroy,
  create,
  data
})

onMounted(function () {
  Object.assign(options, props.config);
  if (options.autoload) {
    // reloadConfig();
  }
});

</script>

<template>
  <div>
    <div style="padding: 0;overflow-x: auto;height: 100%">
      <div id="luckysheet" :style="style"></div>
    </div>
    <n-modal
      v-model:show="showRangePasswordModal"
    >
      <n-card
        style="width: 400px"
        title="密码保护"
        size="huge"
        :bordered="false"
        role="dialog"
        aria-modal="true"
        header-style="padding: 1rem;"
        footer-style="padding: 1rem;text-align: right"
        content-style="padding: 0 1rem;"
      >
        <template #default>
          <n-input v-model:value="password" type="password" placeholder="请输入密码"/>
        </template>
        <template #footer>
          <n-button size="small" @click="showRangePasswordModal = false">取消</n-button>
          <n-button size="small" type="primary" @click="confirmRangePassword" style="margin-left: 1rem">确定</n-button>
        </template>
      </n-card>
    </n-modal>
  </div>


</template>

<style scoped>
.luckysheet {
  position: unset !important;
}
</style>
